package fu.k4c.vTeam.ViewDetails;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Object.Adcom;
import fu.k4c.vTeam.Object.Comment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class CommentActivity extends Activity {
	String email;
	String PlaceID;
	Bundle data;
	String fullName;
	View elementComment;
	ViewGroup commentGroup;
	int CURRENT_TAG = 0;
	static final int TAG_GUEST = 0;
	static final int TAG_USER = 1;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment_activity);
		data = getIntent().getExtras();
		email = data.getString("email");
		fullName = data.getString("fullName");
		if (email.equals("Guest")) {
			CURRENT_TAG = TAG_GUEST;
		} else {
			CURRENT_TAG = TAG_USER;
		}
		PlaceID = data.getString("IDofItemRevision");
		try {
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			HttpParams httpParams = new BasicHttpParams();
			ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
					httpParams, registry);
			HttpClient client = new DefaultHttpClient(connMgr, httpParams);
			HttpPost post = new HttpPost(getString(R.string.connectionString)
					+ "vLocationService/getcomment");
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-type", "application/json");
			HashMap<String, Object> postParameters = new HashMap<String, Object>();
			postParameters.put("IDofItemRevision", PlaceID);
			Gson gson = new Gson();
			String jsonParameters = gson.toJson(postParameters);
			post.setEntity(new StringEntity(jsonParameters));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String jsonresult = EntityUtils.toString(entity);
			Type listType = new TypeToken<ArrayList<Comment>>() {
			}.getType();
			List<Comment> listComments = new Gson().fromJson(jsonresult,
					listType);
			commentGroup = (ViewGroup) findViewById(R.id.layout_comment);
			// Toast.makeText(getApplicationContext(),
			// "size "+listComments.size(), Toast.LENGTH_LONG).show();
			try {
				for (int i = 0; i < listComments.size(); i++) {
					elementComment = LayoutInflater.from(getBaseContext())
							.inflate(R.layout.comment, null);
					commentGroup.addView(elementComment);
					TextView tv_user = (TextView) elementComment
							.findViewById(R.id.tv_comment_user);
					TextView tv_des = (TextView) elementComment
							.findViewById(R.id.tv_comment_des);
					TextView tv_date = (TextView) elementComment
							.findViewById(R.id.tv_comment_date);

					tv_user.setText(listComments.get(i).getUser());
					tv_des.setText(listComments.get(i).getDescription());
					tv_date.setText(listComments.get(i).getDate());
				}
			} catch (Exception e) {
				// TODO: handle exception
				Toast.makeText(getApplicationContext(), "Loi 1" + e.toString(),
						Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(getApplicationContext(), "Loi 2" + e.toString(),
					Toast.LENGTH_LONG).show();
		}
		final Button btn_submit_comment = (Button) findViewById(R.id.btn_view_place_details_submit_comment);
		btn_submit_comment.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText et_comment = (EditText) findViewById(R.id.et_view_place_details_comment);
				if (CURRENT_TAG == 0) {
					Toast.makeText(
							getApplicationContext(),
							"Bạn phải đăng nhập để có thể sử dụng chức năng này",
							Toast.LENGTH_LONG).show();
				} else {
					if (et_comment.getText().toString().trim().length() <= 15) {
						Toast.makeText(getApplicationContext(),
								"Bạn phải nhập nhiều hơn 15 ký tự",
								Toast.LENGTH_LONG).show();
					} else {
						try {
							SchemeRegistry registry = new SchemeRegistry();
							registry.register(new Scheme("http",
									PlainSocketFactory.getSocketFactory(), 80));
							HttpParams httpParams = new BasicHttpParams();
							ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
									httpParams, registry);
							HttpClient client = new DefaultHttpClient(connMgr,
									httpParams);
							HttpPost post = new HttpPost(
									getString(R.string.connectionString)
											+ "vLocationService/AddComment");
							post.setHeader("Accept", "application/json");
							post.setHeader("Content-type", "application/json");
							HashMap<String, Object> postParameters = new HashMap<String, Object>();
							postParameters.put("yourcomment", et_comment
									.getText().toString().trim());
							postParameters.put("idlocation", PlaceID);
							postParameters.put("email", email);
							Gson gson = new Gson();
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters,
									"UTF-8"));
							HttpResponse response = client.execute(post);
							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);
							Adcom fvr = gson.fromJson(jsonresult, Adcom.class);
							// Toast.makeText(getApplicationContext(),
							// jsonresult, Toast.LENGTH_LONG).show();
							if (fvr.getReturnaddcom().equals("true")) {
								elementComment = LayoutInflater.from(
										getBaseContext()).inflate(
										R.layout.comment, null);
								commentGroup.addView(elementComment);
								TextView tv_user = (TextView) elementComment
										.findViewById(R.id.tv_comment_user);
								TextView tv_des = (TextView) elementComment
										.findViewById(R.id.tv_comment_des);
								TextView tv_date = (TextView) elementComment
										.findViewById(R.id.tv_comment_date);
								DateFormat dateFormat = new SimpleDateFormat(
										"dd/MM/yyyy hh:mm:ss");
								Calendar cal = Calendar.getInstance();
								tv_user.setText(fullName);
								tv_des.setText(et_comment.getText().toString());
								if (cal.get(Calendar.AM_PM) == Calendar.PM) {
									tv_date.setText(dateFormat.format(cal
											.getTime()) + " PM");
								} else {
									tv_date.setText(dateFormat.format(cal
											.getTime()) + " AM");
								}

								et_comment.setText("");
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}

			}
		});

	}
}
